﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TSV.Areas.Administration.Models;
using TSV.Library.Common;
using TSV.Models;
using System.IO;
using System.Collections;
using TSV.Library.Attributes;
namespace TSV.Areas.Administration.Controllers
{
    public class AdvertisingController : BaseController
    {
        AdvertisingDao AD = new AdvertisingDao();
        public ActionResult GetListJQGrid()
        {

            #region JQGrid Params

            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
            #endregion

            List<sp_GetAdvertisingResult> ADList = AD.GetList().ToList<sp_GetAdvertisingResult>();

            int totalRecords = ADList.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);

            var finalList = AD.Sort(ADList, sortColumn, sortOrder)
                                  .Skip((pageIndex - 1) * rowCount)
                                   .Take(rowCount);
            int j = 0;

            var jsonData = new
            {
                total = totalPages,
                page = pageIndex,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {

                        i = m.ID,
                        cell = new string[] {
                                Convert.ToString(j+=1),
                                m.ID.ToString(), 
                                TooltipLink("/Administration/Advertising/Edit/"+m.ID.ToString(),HttpUtility.HtmlEncode(m.Image)),
                                HttpUtility.HtmlEncode(m.Title),
                                "<input type='button' name='btnMoveUp' class='icon moveup' title='Chuyển mẫu tin lên trên' onclick=\"JS_LIB.redirect('/Administration/Advertising/MoveUp/?id=" + m.ID.ToString() +"')\" />"
                            +"<input type='button' name='btnMoveDown' class='icon movedown' title='Chuyển mẫu tin xuống dưới' onclick=\"JS_LIB.redirect('/Administration/Advertising/MoveDown/?id=" + m.ID.ToString() + "')\"/>",
                                getPossition(m.Position),
                                HttpUtility.HtmlEncode(m.ExternalLink),
                                CommonFunc.ShowActiveImage(m.IsIntenalLink),
                                CommonFunc.ButtonEdit("/Administration/Advertising/Edit/"+m.ID.ToString()),
                                
                            }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        private string getPossition(string pos)
        {
            switch (pos.ToUpper())
            {
                case "L" :
                    return "Trái";
                case "R":
                    return "Phải";
                case "T":
                    return "Trên";
                case "B":
                    return "Dưới";
                default:
                    return "";
                
            }
            
        }
        private string TooltipLink(string actionUrl, string textLink)
        {
            string onclick = string.Format("window.location='{0}';", actionUrl);
            string jsvoid = "javascript:void(0);";
            int[] size = CommonFunc.FixImageSize(210,100,Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH + textLink));
            //System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH + textLink));
            //int w, h;
            //h = objImage.Height > 100 ? 100 : objImage.Height;
            //w = objImage.Width > 210 ? 210 : objImage.Width;
            string imageTag = string.Format("<img height='{0}px' width='{1}px' src={2} />", size[1], size[0], Constants.UPLOAD_ADV_IMAGE_PATH + textLink);
            string str = string.Format("<a id=\"textlnk\" href=\"{0}\" class=\"showTooltip\" onclick=\"{1}\">{2}</a>", jsvoid, onclick, imageTag);
            return str;
        }
        //
        // GET: /Administration/Advertising/
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            return View();
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Them)]
        public ActionResult Create()
        {
            ViewData["Position"] = new SelectList(Constants.ADV_POSITION, "Value", "Text", string.Empty);
            return View();
        }
        private Message CheckUploadImage(HttpPostedFileBase file)
        {
            if (file.FileName == String.Empty)
                return null;
            Message msg = null;
            string ext = Path.GetExtension(file.FileName);
            if (file.ContentLength > Constants.UPLOAD_FILE_SIZE*1024*1024)
            {
                msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.UPLOAD_FILE_SIZE);
            }
            else if (!Constants.UPLOAD_ALLOW_IMG_EXT.Split(',').Contains(ext))
            {
                msg = new Message(MessageConstants.E0013, MessageType.Error, ext, Constants.UPLOAD_ALLOW_IMG_EXT, Constants.UPLOAD_FILE_SIZE);
            }
            return msg;

        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Them)]
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Advertising obj, HttpPostedFileBase file)
        {
            JsonResult result = new JsonResult();
            result.ContentType = "text/html";
            result.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Message msg = CheckUploadImage(file);
            if (string.IsNullOrEmpty(obj.Description) && obj.IsIntenalLink==true)
            {
                msg = new Message(MessageConstants.E0043, MessageType.Error, "");
            }
            if (msg == null)
            {
                    string uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + file.FileName;
                    string path = Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH) + uniqueName;
                    file.SaveAs(path);
                    obj.Image = uniqueName;
                    obj.ExternalLink = obj.IsIntenalLink == false ? obj.ExternalLink : "";
                    //obj.AdOrder = obj.AdOrder.ToString().Trim() != "" ? obj.AdOrder : 0;
                    obj.AdOrder = AD.GetLastOrder()+1;
                    msg = AD.Insert(obj);
                    ShowMessage(msg);
                
            }
            result.Data = msg;
            return result;
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Xoa)]
        public ActionResult DeleteList(string id)
        {
            Message msg=null;
            try
            {
                string[] idArr = id.Split(',');
                ArrayList pathList = new ArrayList();
                foreach (string index in idArr)
                {
                    Advertising oscObj = AD.GetById(index);
                    if (oscObj != null)
                    {
                        string path = Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH + oscObj.Image);
                        pathList.Add(path);
                    }

                }

                msg = AD.DeleteList(id);
                foreach (string p in pathList)
                    if (System.IO.File.Exists(p))
                        System.IO.File.Delete(p);
                
                
            }catch(Exception){
                msg = new Message(MessageConstants.E0007, MessageType.Error);
                
            }
            ShowMessage(msg);
            return RedirectToAction("Index");
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Sua)]
        public ActionResult Edit(int id)
        {
            Advertising oscObj = AD.GetById(id.ToString());
            ViewData["Position"] = new SelectList(Constants.ADV_POSITION, "Value", "Text", oscObj.Position);
            
            return View(oscObj);
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Quang_Cao, Rights = Permissions.Sua)]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(Advertising obj, HttpPostedFileBase file)
        {
            JsonResult result = new JsonResult();
            result.ContentType = "text/html";
            result.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Message msg=null;
            if (string.IsNullOrEmpty(obj.Description) && obj.IsIntenalLink == true)
            {
                msg = new Message(MessageConstants.E0043, MessageType.Error, "");
            }
            else
            {
                if (file != null)
                {
                    msg = CheckUploadImage(file);
                    if (msg == null)
                    {
                        string uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + file.FileName;
                        string path = Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH) + uniqueName;
                        file.SaveAs(path);
                        string old_path = Server.MapPath(Constants.UPLOAD_ADV_IMAGE_PATH) + obj.Image;
                        if (System.IO.File.Exists(old_path))
                            System.IO.File.Delete(old_path);
                            obj.Image = uniqueName;

                    }
                }
                msg = AD.Update(obj);
            }
            ShowMessage(msg);
            result.Data = msg;
            return result;
        }
        public ActionResult MoveUp(string id)
        {
            Advertising adv = AD.GetById(id);
            Message msg = AD.MoveUp(adv);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }

        public ActionResult MoveDown(string id)
        {
            Advertising adv = AD.GetById(id);
            Message msg = AD.MoveDown(adv);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }
    }
}
